package com.libre.security;

import com.libre.auth.mapper.RolePermissionMapper;
import com.libre.common.constant.SysConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

// 自定义UrlFilterInvocationSecurityMetadataSource实现FilterInvocationSecurityMetadataSource重写getAttributes()方法 获取访问该url所需要的角色权限信息
@Slf4j
@Component
public class UrlFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    RolePermissionMapper rolePermissionMapper;

    /***
     * 返回该url所需要的用户权限信息
     *
     * @param object: 储存请求url信息
     * @return: null：标识不需要任何权限都可以访问
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        log.info(">>>>>>>>> 进入getAttributes鉴权 >>>>>>>>>");
        /**
         * 获取当前请求url
         * String requestUrl = ((FilterInvocation) object).getFullRequestUrl();//完整的请求Url
         * String requestUrl = ((FilterInvocation) object).getRequestUrl();//URL地址(包括参数)
         * */
        HttpServletRequest httpRequest = ((FilterInvocation) object).getHttpRequest();
        String uri = httpRequest.getRequestURI();
        System.out.println("请求路径==" + httpRequest.getRequestURI());
        // TODO 忽略url请放在此处进行过滤放行,后期去掉
        if ("/permission/menuTree".equals(uri)) {
            return null;
        }
        // 通过url查询当前url对应的所有角色
        List<String> codes = rolePermissionMapper.findRoleCodeByUrl(uri);
        //SecurityConfig.createList 不能为空，否则放过直接放过，不进行拦截
        if (codes.size() > 0) {
            // 将url对应的所有角色都放入
            return SecurityConfig.createList(codes.toArray(new String[codes.size()]));
        } else {
            // 如果数据中没有找到相应url资源则为非法访问，要求用户登录再进行操作
            return SecurityConfig.createList(SysConstant.ROLE_LOGIN);
        }
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}

